package cn.wolfcode.trip.admin.controller;


import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("region")
public class regionController {
    @Autowired
    private IRegionService regionService;

    /**
     * 加载页面
     * @return
     */
    @RequestMapping("list")
    public String list() {

        return "/region/list";
    }


    /**
     * 查询所有地区
     * @return
     */
    @RequestMapping("listAll")
    @ResponseBody
    public List<Region> listAll() {

        return regionService.listAll(null);
    }

    /**
     * 修改状态
     * @return
     */
    @RequestMapping("changeState")
    @ResponseBody
    public JSONResult changeState(Region region) {
        JSONResult jsonResult = new JSONResult();
        regionService.changeState(region);
        return jsonResult;
    }

    /**
     * 新增和编辑
     * @param region
     * @return
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Region region) {
        JSONResult jsonResult = new JSONResult();

        regionService.saveOrUpdate(region);
        return jsonResult;
    }


    /**
     * 查询地区
     * @param parentId 参数为null 查询根地区
     * @param type 参数为tree 查询结构处理成treeview数据
     * @return
     */
    @RequestMapping("selectByParentId")
    @ResponseBody
    public List list(Long parentId, String type) {
        //查询地区
        List<Region> regions = regionService.selectByParentId(parentId);
        //判断是否需要treeview数据
        if ("tree".equals(type)) {
            //用来存放tree要的格式数据
            List list = new ArrayList();
            //遍历集合regions
            for (Region region : regions) {
                //取出regions里的地区对象,对数据进行处理成tree插件需要的格式
                list.add(region.toTreeMap());
            }
            return list;
        } else {
            return regions;
        }
    }

}
